package com.xueyi.aixihu.interceptors;

import cn.hutool.core.date.DateUtil;
import com.xueyi.aixihu.exception.SzException;
import com.xueyi.aixihu.mapper.FinanceMapper;
import com.xueyi.aixihu.service.IFinanceReportService;
import com.xueyi.aixihu.utils.FinalUtil;
import com.xueyi.aixihu.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.Date;

/**
 * 描述 用户访问切面
 *
 * @auther 俞烨
 * @date 2022-08-31 10
 */
@Aspect
@Component
@Slf4j
public class RequestSizeAspect {

    @Autowired
    FinanceMapper financeMapper;
    @Autowired
    IFinanceReportService iFinanceReportService;


    @Before("execution(public * com.xueyi.aixihu.controller.*.*(..))")
    public void requestSize() {

        Jedis jedis = null;
        try {
            jedis = JedisUtil.getJedis();
            jedis.incr("TODAY_REQ_SIZE:" + DateUtil.format(new Date(), "yyyy-MM-dd"));
            jedis.expire("TODAY_REQ_SIZE:" + DateUtil.format(new Date(), "yyyy-MM-dd"), 3600 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FinalUtil.unLockAndCloseRedis(jedis);
        }
    }

    @Scheduled(cron = "0 0 0/12 * * ?")
    public void notifySize() {
        try {
            iFinanceReportService.findNotifyList();
        } catch (SzException e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0 50 23 * * ?")
    public void synToDayReqSize() {
        Jedis jedis = JedisUtil.getJedis();
        try {
            String timeFormat = DateUtil.format(new Date(), "yyyy-MM-dd");
            String totalReqSize = jedis.get("TODAY_REQ_SIZE:" + timeFormat);
            int reqSize = StringUtils.isBlank(totalReqSize) ? 0 : Integer.parseInt(totalReqSize);
            log.info("新增请求数量: {} , {}", timeFormat, reqSize);
            financeMapper.saveReqSize(reqSize);
        } finally {
            FinalUtil.unLockAndCloseRedis(jedis);
        }
    }
}
